<template>
  <div class="space-y-6">
    <!-- 页面标题 -->
    <div>
      <h1 class="text-2xl font-bold text-gray-900">系统设置</h1>
      <p class="text-gray-600 mt-1">管理系统配置和用户权限</p>
    </div>
    
    <!-- 设置选项卡 -->
    <el-card>
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 基本设置 -->
        <el-tab-pane label="基本设置" name="basic">
          <div class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <!-- 系统信息 -->
              <el-card class="h-fit">
                <template #header>
                  <span class="font-medium">系统信息</span>
                </template>
                <div class="space-y-3">
                  <div class="flex justify-between">
                    <span class="text-gray-600">系统名称:</span>
                    <span class="font-medium">车辆管理系统</span>
                  </div>
                  <div class="flex justify-between">
                    <span class="text-gray-600">版本号:</span>
                    <span class="font-medium">v1.0.0</span>
                  </div>
                  <div class="flex justify-between">
                    <span class="text-gray-600">最后更新:</span>
                    <span class="font-medium">2024-01-15</span>
                  </div>
                  <div class="flex justify-between">
                    <span class="text-gray-600">运行时间:</span>
                    <span class="font-medium">15天 8小时</span>
                  </div>
                </div>
              </el-card>
              
              <!-- 系统配置 -->
              <el-card class="h-fit">
                <template #header>
                  <span class="font-medium">系统配置</span>
                </template>
                <el-form :model="systemConfig" label-width="120px">
                  <el-form-item label="系统名称">
                    <el-input v-model="systemConfig.systemName" placeholder="请输入系统名称" />
                  </el-form-item>
                  <el-form-item label="公司名称">
                    <el-input v-model="systemConfig.companyName" placeholder="请输入公司名称" />
                  </el-form-item>
                  <el-form-item label="联系电话">
                    <el-input v-model="systemConfig.contactPhone" placeholder="请输入联系电话" />
                  </el-form-item>
                  <el-form-item label="系统主题">
                    <el-select v-model="systemConfig.theme" placeholder="选择主题" class="w-full">
                      <el-option label="默认主题" value="default" />
                      <el-option label="深色主题" value="dark" />
                      <el-option label="蓝色主题" value="blue" />
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="saveSystemConfig">保存配置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </div>
            
            <!-- 功能开关 -->
            <el-card>
              <template #header>
                <span class="font-medium">功能开关</span>
              </template>
              <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div>
                    <h4 class="font-medium text-gray-900">自动备份</h4>
                    <p class="text-sm text-gray-600">每日自动备份数据</p>
                  </div>
                  <el-switch v-model="features.autoBackup" />
                </div>
                <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div>
                    <h4 class="font-medium text-gray-900">邮件通知</h4>
                    <p class="text-sm text-gray-600">重要事件邮件提醒</p>
                  </div>
                  <el-switch v-model="features.emailNotification" />
                </div>
                <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div>
                    <h4 class="font-medium text-gray-900">短信通知</h4>
                    <p class="text-sm text-gray-600">紧急情况短信提醒</p>
                  </div>
                  <el-switch v-model="features.smsNotification" />
                </div>
                <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div>
                    <h4 class="font-medium text-gray-900">GPS追踪</h4>
                    <p class="text-sm text-gray-600">实时车辆位置追踪</p>
                  </div>
                  <el-switch v-model="features.gpsTracking" />
                </div>
                <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div>
                    <h4 class="font-medium text-gray-900">维护提醒</h4>
                    <p class="text-sm text-gray-600">车辆维护到期提醒</p>
                  </div>
                  <el-switch v-model="features.maintenanceReminder" />
                </div>
                <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                  <div>
                    <h4 class="font-medium text-gray-900">数据统计</h4>
                    <p class="text-sm text-gray-600">生成使用统计报告</p>
                  </div>
                  <el-switch v-model="features.dataAnalytics" />
                </div>
              </div>
              <div class="mt-6">
                <el-button type="primary" @click="saveFeatures">保存设置</el-button>
              </div>
            </el-card>
          </div>
        </el-tab-pane>
        
        <!-- 用户管理 -->
        <el-tab-pane label="用户管理" name="users">
          <div class="space-y-6">
            <!-- 用户操作 -->
            <div class="flex items-center justify-between">
              <div class="flex items-center space-x-4">
                <el-input
                  v-model="userSearchQuery"
                  placeholder="搜索用户名或邮箱"
                  :prefix-icon="Search"
                  clearable
                  class="w-64"
                />
                <el-select v-model="roleFilter" placeholder="角色筛选" clearable class="w-32">
                  <el-option label="管理员" value="admin" />
                  <el-option label="员工" value="employee" />
                  <el-option label="驾驶员" value="driver" />
                </el-select>
              </div>
              <el-button type="primary" :icon="Plus" @click="showAddUserDialog = true">
                添加用户
              </el-button>
            </div>
            
            <!-- 用户列表 -->
            <el-card>
              <el-table :data="filteredUsers" stripe style="width: 100%">
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column label="头像" width="80">
                  <template #default="{ row }">
                    <el-avatar :src="row.avatar" :icon="UserFilled" />
                  </template>
                </el-table-column>
                <el-table-column prop="username" label="用户名" width="120" />
                <el-table-column prop="email" label="邮箱" width="200" />
                <el-table-column prop="phone" label="电话" width="130" />
                <el-table-column label="角色" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getRoleType(row.role)" size="small">
                      {{ getRoleText(row.role) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="row.status === 'active' ? 'success' : 'danger'" size="small">
                      {{ row.status === 'active' ? '正常' : '禁用' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="lastLogin" label="最后登录" width="150" />
                <el-table-column prop="createdAt" label="创建时间" width="150" />
                <el-table-column label="操作" width="200" fixed="right">
                  <template #default="{ row }">
                    <el-button size="small" @click="viewUser(row)">查看</el-button>
                    <el-button size="small" type="primary" @click="editUser(row)">编辑</el-button>
                    <el-button 
                      size="small" 
                      :type="row.status === 'active' ? 'warning' : 'success'"
                      @click="toggleUserStatus(row)"
                    >
                      {{ row.status === 'active' ? '禁用' : '启用' }}
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-tab-pane>
        
        <!-- 权限管理 -->
        <el-tab-pane label="权限管理" name="permissions">
          <div class="space-y-6">
            <el-card>
              <template #header>
                <span class="font-medium">角色权限配置</span>
              </template>
              <div class="space-y-6">
                <el-select v-model="selectedRole" placeholder="选择角色" class="w-48">
                  <el-option label="管理员" value="admin" />
                  <el-option label="员工" value="employee" />
                  <el-option label="驾驶员" value="driver" />
                </el-select>
                
                <div v-if="selectedRole" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                  <div v-for="module in permissionModules" :key="module.name" class="border rounded-lg p-4">
                    <div class="flex items-center justify-between mb-3">
                      <h4 class="font-medium text-gray-900">{{ module.label }}</h4>
                      <el-switch 
                        v-model="module.enabled" 
                        @change="toggleModulePermission(module.name, module.enabled)"
                      />
                    </div>
                    <div v-if="module.enabled" class="space-y-2">
                      <div v-for="permission in module.permissions" :key="permission.name" class="flex items-center justify-between">
                        <span class="text-sm text-gray-600">{{ permission.label }}</span>
                        <el-checkbox 
                          v-model="permission.granted" 
                          @change="updatePermission(module.name, permission.name, permission.granted)"
                        />
                      </div>
                    </div>
                  </div>
                </div>
                
                <div class="mt-6">
                  <el-button type="primary" @click="savePermissions">保存权限配置</el-button>
                </div>
              </div>
            </el-card>
          </div>
        </el-tab-pane>
        
        <!-- 系统日志 -->
        <el-tab-pane label="系统日志" name="logs">
          <div class="space-y-6">
            <!-- 日志筛选 -->
            <el-card>
              <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <el-select v-model="logLevelFilter" placeholder="日志级别" clearable>
                  <el-option label="信息" value="info" />
                  <el-option label="警告" value="warning" />
                  <el-option label="错误" value="error" />
                  <el-option label="调试" value="debug" />
                </el-select>
                <el-select v-model="logModuleFilter" placeholder="模块" clearable>
                  <el-option label="用户管理" value="user" />
                  <el-option label="车辆管理" value="vehicle" />
                  <el-option label="申请管理" value="application" />
                  <el-option label="系统设置" value="system" />
                </el-select>
                <el-date-picker
                  v-model="logDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
                <el-button @click="refreshLogs">刷新日志</el-button>
              </div>
            </el-card>
            
            <!-- 日志列表 -->
            <el-card>
              <el-table :data="filteredLogs" stripe style="width: 100%" max-height="500">
                <el-table-column prop="timestamp" label="时间" width="180" />
                <el-table-column label="级别" width="80">
                  <template #default="{ row }">
                    <el-tag :type="getLogLevelType(row.level)" size="small">
                      {{ row.level.toUpperCase() }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="module" label="模块" width="100" />
                <el-table-column prop="user" label="用户" width="100" />
                <el-table-column prop="action" label="操作" width="150" />
                <el-table-column prop="message" label="详细信息" min-width="200" />
                <el-table-column prop="ip" label="IP地址" width="120" />
              </el-table>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 添加用户对话框 -->
    <el-dialog v-model="showAddUserDialog" title="添加用户" width="500px">
      <el-form :model="userForm" :rules="userRules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="选择角色" class="w-full">
            <el-option label="管理员" value="admin" />
            <el-option label="员工" value="employee" />
            <el-option label="驾驶员" value="driver" />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelAddUser">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, UserFilled } from '@element-plus/icons-vue'

// 接口定义
interface User {
  id: number
  username: string
  email: string
  phone: string
  role: 'admin' | 'employee' | 'driver'
  status: 'active' | 'inactive'
  lastLogin: string
  createdAt: string
  avatar?: string
}

interface SystemLog {
  id: number
  timestamp: string
  level: 'info' | 'warning' | 'error' | 'debug'
  module: string
  user: string
  action: string
  message: string
  ip: string
}

// 响应式数据
const activeTab = ref('basic')
const showAddUserDialog = ref(false)
const userSearchQuery = ref('')
const roleFilter = ref('')
const selectedRole = ref('')
const logLevelFilter = ref('')
const logModuleFilter = ref('')
const logDateRange = ref<[string, string] | null>(null)

// 系统配置
const systemConfig = reactive({
  systemName: '车辆管理系统',
  companyName: '某某科技有限公司',
  contactPhone: '400-123-4567',
  theme: 'default'
})

// 功能开关
const features = reactive({
  autoBackup: true,
  emailNotification: true,
  smsNotification: false,
  gpsTracking: true,
  maintenanceReminder: true,
  dataAnalytics: true
})

// 用户表单
const userForm = reactive({
  username: '',
  email: '',
  phone: '',
  role: '' as User['role'],
  password: ''
})

// 表单验证规则
const userRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 权限模块
const permissionModules = ref([
  {
    name: 'vehicle',
    label: '车辆管理',
    enabled: true,
    permissions: [
      { name: 'view', label: '查看', granted: true },
      { name: 'create', label: '创建', granted: true },
      { name: 'edit', label: '编辑', granted: true },
      { name: 'delete', label: '删除', granted: false }
    ]
  },
  {
    name: 'application',
    label: '申请管理',
    enabled: true,
    permissions: [
      { name: 'view', label: '查看', granted: true },
      { name: 'create', label: '创建', granted: true },
      { name: 'approve', label: '审批', granted: false },
      { name: 'reject', label: '拒绝', granted: false }
    ]
  },
  {
    name: 'driver',
    label: '驾驶员管理',
    enabled: true,
    permissions: [
      { name: 'view', label: '查看', granted: true },
      { name: 'create', label: '创建', granted: false },
      { name: 'edit', label: '编辑', granted: false },
      { name: 'delete', label: '删除', granted: false }
    ]
  },
  {
    name: 'expense',
    label: '费用管理',
    enabled: true,
    permissions: [
      { name: 'view', label: '查看', granted: true },
      { name: 'create', label: '创建', granted: true },
      { name: 'edit', label: '编辑', granted: false },
      { name: 'delete', label: '删除', granted: false }
    ]
  },
  {
    name: 'system',
    label: '系统设置',
    enabled: false,
    permissions: [
      { name: 'view', label: '查看', granted: false },
      { name: 'edit', label: '编辑', granted: false }
    ]
  }
])

// 模拟用户数据
const users = ref<User[]>([
  {
    id: 1,
    username: 'admin',
    email: 'admin@example.com',
    phone: '13800138001',
    role: 'admin',
    status: 'active',
    lastLogin: '2024-01-15 10:30:00',
    createdAt: '2023-01-01 00:00:00'
  },
  {
    id: 2,
    username: 'employee1',
    email: 'employee1@example.com',
    phone: '13800138002',
    role: 'employee',
    status: 'active',
    lastLogin: '2024-01-15 09:15:00',
    createdAt: '2023-06-15 00:00:00'
  },
  {
    id: 3,
    username: 'driver1',
    email: 'driver1@example.com',
    phone: '13800138003',
    role: 'driver',
    status: 'active',
    lastLogin: '2024-01-14 18:45:00',
    createdAt: '2023-08-20 00:00:00'
  }
])

// 模拟系统日志
const systemLogs = ref<SystemLog[]>([
  {
    id: 1,
    timestamp: '2024-01-15 10:30:15',
    level: 'info',
    module: 'user',
    user: 'admin',
    action: '用户登录',
    message: '管理员用户登录成功',
    ip: '192.168.1.100'
  },
  {
    id: 2,
    timestamp: '2024-01-15 10:25:30',
    level: 'warning',
    module: 'vehicle',
    user: 'employee1',
    action: '车辆状态变更',
    message: '车辆京A12345状态变更为维护中',
    ip: '192.168.1.101'
  },
  {
    id: 3,
    timestamp: '2024-01-15 10:20:45',
    level: 'error',
    module: 'system',
    user: 'system',
    action: '数据备份',
    message: '自动备份失败：磁盘空间不足',
    ip: '127.0.0.1'
  }
])

// 计算属性
const filteredUsers = computed(() => {
  let filtered = users.value
  
  if (userSearchQuery.value) {
    const query = userSearchQuery.value.toLowerCase()
    filtered = filtered.filter(user => 
      user.username.toLowerCase().includes(query) ||
      user.email.toLowerCase().includes(query)
    )
  }
  
  if (roleFilter.value) {
    filtered = filtered.filter(user => user.role === roleFilter.value)
  }
  
  return filtered
})

const filteredLogs = computed(() => {
  let filtered = systemLogs.value
  
  if (logLevelFilter.value) {
    filtered = filtered.filter(log => log.level === logLevelFilter.value)
  }
  
  if (logModuleFilter.value) {
    filtered = filtered.filter(log => log.module === logModuleFilter.value)
  }
  
  if (logDateRange.value && logDateRange.value.length === 2) {
    const [start, end] = logDateRange.value
    filtered = filtered.filter(log => {
      const logDate = log.timestamp.split(' ')[0]
      return logDate >= start && logDate <= end
    })
  }
  
  return filtered.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
})

// 方法
const getRoleType = (role: User['role']) => {
  const types = {
    admin: 'danger',
    employee: 'primary',
    driver: 'success'
  }
  return types[role]
}

const getRoleText = (role: User['role']) => {
  const texts = {
    admin: '管理员',
    employee: '员工',
    driver: '驾驶员'
  }
  return texts[role]
}

const getLogLevelType = (level: SystemLog['level']) => {
  const types = {
    info: 'primary',
    warning: 'warning',
    error: 'danger',
    debug: 'info'
  }
  return types[level]
}

const saveSystemConfig = () => {
  ElMessage.success('系统配置保存成功')
}

const saveFeatures = () => {
  ElMessage.success('功能设置保存成功')
}

const viewUser = (user: User) => {
  ElMessage.info(`查看用户: ${user.username}`)
}

const editUser = (user: User) => {
  ElMessage.info(`编辑用户: ${user.username}`)
}

const toggleUserStatus = (user: User) => {
  const action = user.status === 'active' ? '禁用' : '启用'
  ElMessageBox.confirm(
    `确定要${action}用户 ${user.username} 吗？`,
    `确认${action}`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    user.status = user.status === 'active' ? 'inactive' : 'active'
    ElMessage.success(`用户${action}成功`)
  })
}

const saveUser = () => {
  const newUser: User = {
    id: Date.now(),
    ...userForm,
    status: 'active',
    lastLogin: '-',
    createdAt: new Date().toLocaleString('zh-CN')
  }
  users.value.push(newUser)
  ElMessage.success('用户添加成功')
  cancelAddUser()
}

const cancelAddUser = () => {
  showAddUserDialog.value = false
  Object.assign(userForm, {
    username: '',
    email: '',
    phone: '',
    role: '',
    password: ''
  })
}

const toggleModulePermission = (moduleName: string, enabled: boolean) => {
  const module = permissionModules.value.find(m => m.name === moduleName)
  if (module && !enabled) {
    module.permissions.forEach(p => p.granted = false)
  }
}

const updatePermission = (moduleName: string, permissionName: string, granted: boolean) => {
  // 更新权限逻辑
}

const savePermissions = () => {
  ElMessage.success('权限配置保存成功')
}

const refreshLogs = () => {
  ElMessage.success('日志已刷新')
}

// 组件挂载时加载数据
onMounted(() => {
  // 这里可以调用API加载实际数据
})
</script>

<style scoped>
.el-card {
  border-radius: 8px;
}

.el-tabs {
  border-radius: 8px;
}

.el-table {
  border-radius: 8px;
}
</style>